﻿param($exportPath)
# Import the Active Directory module for the Get-ADComputer CmdLet 

 
# Query Active Directory for computers running a Server operating system 


workflow Get-RDPSessionInfo
{
    
    $computers = (Get-ADComputer -Filter {OperatingSystem -like "*server*"}).DNSHostName

    foreach -Parallel($computer in $computers )
    {
        InlineScript
        {
            
            Import-Module c:\codeplex\Windows\PSTerminalServices\PSTerminalServices.psm1

            Add-Type -Path c:\codeplex\Windows\PSTerminalServices\Bin\Cassia.dll
            $sessions=Get-TSSession -ComputerName $using:computer -ErrorAction SilentlyContinue | Where {$_.UserName -ne $null -and $_.UserName -ne ""} | select @{Expression={$using:computer};Label="ComputerName"},DomainName,UserName,ConnectionState,ConnectTime,DisconnectTime,LastInputTime,LoginTime,IdleTime

            foreach($session in $sessions)
            {
                $owners = @{}
                $memoryUsed=0

                gwmi win32_process -ComputerName $using:computer |% -ErrorAction SilentlyContinue {$owners[$_.handle] = $_.getowner().user}

                $memoryUsed=(get-process -ComputerName $using:computer | select processname,Id,@{l="Owner";e={$owners[$_.id.tostring()]}},WorkingSet | where {$_.Owner -eq $Session.UserName} | Measure-Object -Sum -Property WorkingSet).Sum/1GB

                New-Object PSObject -Property @{ComputerName=$session.ComputerName;
                                                DomainName=$session.DomainName;
                                                UserName=$session.UserName;
                                                ConnectionState=$session.ConnectionState;
                                                ConnectTime=$session.ConnectTime;
                                                DisconnectTime=$session.DisconnectTime;
                                                LastInputTime=$session.LastInputTime;
                                                LoginTime=$session.LoginTime;
                                                IdleTime=$session.IdleTime;
                                                MemoryUsed=$memoryUsed;}
            }


        }
    }
   
} 

Get-RDPSessionInfo | Export-csv -Path $exportPath -NoTypeInformation -Force